const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
const chokidar = require('chokidar');
const cors = require('cors');
// 在文件顶部添加


// 在 app.listen 前添加这些测试端点
// 健康检查端点
app.get('/', (req, res) => {
    res.send(`
        <h1>Message Notification Service</h1>
        <p>Service is running. Endpoints:</p>
        <ul>
            <li><a href="/test">Test endpoint</a></li>
            <li><a href="/notifications">SSE Notifications</a></li>
        </ul>
    `);
});

// 测试端点
app.get('/test', (req, res) => {
    // 检查文件系统权限
    const testFilePath = path.join(SHARED_CHATS_DIR, 'test.json');
    const testData = `{"test": "File ${new Date().toISOString()}"}`;
    
    try {
        fs.writeFileSync(testFilePath, testData);
        const content = fs.readFileSync(testFilePath, 'utf8');
        
        res.json({
            status: "success",
            port: PORT,
            directory: SHARED_CHATS_DIR,
            fileWrite: content === testData
        });
    } catch (err) {
        res.status(500).json({
            status: "error",
            error: err.message,
            directory: SHARED_CHATS_DIR
        });
    }
});
// 配置
const PORT = 3113;
const SHARED_CHATS_DIR = path.join(__dirname, 'messages', 'shared_chats');

// 使用内存缓存而不是写入文件
const messageChanges = {};
const clientSubscriptions = new Set();

// 支持跨域请求
app.use(cors());
app.use(express.json());

// 监听文件变化
const watcher = chokidar.watch(SHARED_CHATS_DIR, {
    persistent: true,
    ignored: /(^|[\/\\])\../, // 忽略隐藏文件
    ignoreInitial: true,       // 忽略启动时的扫描
    depth: 0,
    usePolling: false,
    interval: 1000,
    binaryInterval: 3000,
    alwaysStat: false,
    useFsEvents: true,
});

watcher
    .on('add', handleFileChange)
    .on('change', handleFileChange);

function handleFileChange(filePath) {
    const filename = path.basename(filePath);
    const [sender, receiver] = filename.split('_').map(n => n.replace('.json', ''));
    
    if (!messageChanges[receiver]) {
        messageChanges[receiver] = new Set();
    }
    
    messageChanges[receiver].add(sender);
    notifyClients();
}

// 通知所有订阅的客户端
function notifyClients() {
    clientSubscriptions.forEach(res => {
        res.write(`data: ${JSON.stringify({type: 'update'})}\n\n`);
    });
}

// SSE 端点用于推送通知
app.get('/notifications', (req, res) => {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.flushHeaders();
    
    // 心跳检测保持连接
    const heartbeat = setInterval(() => {
        res.write(':heartbeat\n\n');
    }, 25000);
    
    clientSubscriptions.add(res);
    
    req.on('close', () => {
        clearInterval(heartbeat);
        clientSubscriptions.delete(res);
        res.end();
    });
});

// 获取新消息的API
app.get('/new-messages/:username', (req, res) => {
    const username = req.params.username;
    const changes = messageChanges[username] || [];
    
    // 响应后清除该用户的通知
    delete messageChanges[username];
    
    res.json({
        success: true,
        newMessages: Array.from(changes)
    });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`Message notification server running on port ${PORT}`);
    console.log(`Watching directory: ${SHARED_CHATS_DIR}`);
});